// dialog入口文件
import dialogComponent from "./Dialog.vue";

let dialogConstructor;
let dialogDom; // 组件实例,同时最多只能存在一个组件，前生成的会被后生成的覆盖
let deg = 0;
// 组件方法
const dialog = {
  hide: () => {
    // 去除组件
    if (dialogDom) {
      document.body.removeChild(dialogDom.$el);
      dialogDom = false;
    }
    deg = 0;
  },
  //旋转图片
  rotate: (flag) => {
    dialogDom.$refs.imgBox.style.transition = `all 0.2s linear`;
    if (flag) {
      dialogDom.$refs.imgBox.style.transform = `rotate(${deg + 90}deg)`;
      deg += 90;
    } else {
      dialogDom.$refs.imgBox.style.transform = `rotate(${deg - 90}deg)`;
      deg -= 90;
    }
  },
  // 普通弹窗
  alert: (data, resolve, reject, rotateFn) => {
    // 初始化组件
    if (dialogDom) {
      document.body.removeChild(dialogDom.$el);
      dialogDom = false;
    }
    data.type = "alert";
    dialogDom = new dialogConstructor({
      el: document.createElement("div"),
      data() {
        return data;
      },
      methods: {
        sureBtnFn() {
          resolve();
        },
        closeConfirm() {
          reject();
        },
        rotate(flag) {
          rotateFn(flag);
        },
      },
    });
    // 把 实例化的 dialog.vue 添加到 body 里
    document.body.appendChild(dialogDom.$el);
  },
  // Confirm弹窗
  show: (data, resolve, reject) => {
    // 初始化组件
    if (dialogDom) {
      document.body.removeChild(dialogDom.$el);
      dialogDom = false;
    }
    data.type = "confirm";
    dialogDom = new dialogConstructor({
      el: document.createElement("div"),
      data() {
        return data;
      },
      methods: {
        sureBtnFn() {
          resolve();
        },
        closeConfirm() {
          reject();
        },
      },
    });
    // 把 实例化的 dialog.vue 添加到 body 里
    document.body.appendChild(dialogDom.$el);
  },
};

export default function install(Vue) {
  dialogConstructor = Vue.extend(dialogComponent);
  // 将组件注册到 vue 的 原型链里去
  Vue.prototype.$dialogConfirm = dialog;
}
